<?php

namespace app\index\dao;

use app\common\model\ProfessionalQa;
use ShidianUtil\Thinkphp\Dao\DaoTrait;
use think\Collection;

/**
 * ProfessionalQaDao 数据访问对象
 * Class ProfessionalQaDao
 * @package app\dao
 * @method ProfessionalQa findByPK(?int $id, $field = true)
 * @method \think\Collection selectAll(?int $page, ?int $page_size, $field = true)
 * @method ProfessionalQa insertActive(array $params, array $allow_field = [])
 * @method ProfessionalQa updateActive(ProfessionalQa $model, array $params, array $allow_field = [])
 * @method ProfessionalQa findAndUpdateActive(int $id, array $params, array $allow_field = [])
 * @method ProfessionalQa updateActiveByClosure(\Closure $closure, array $params, array $allow_field = [])
 * @method void deleteModel(ProfessionalQa $model)
 * @method void deleteById(int|array|\Closure $id, bool $force = false)
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class ProfessionalQaDao
{
    use DaoTrait;

    /**
     * @var \app\common\model\ProfessionalQa
     */
    private $baseModel;

    /**
     * ProfessionalQaDao constructor.
     */
    public function __construct()
    {
        $this->baseModel = ProfessionalQa::class;
    }

    /**
     * 首页
     * @param $cityId
     * @param int $number
     * @return Collection
     */
    public function selectHome($cityId, int $number): Collection
    {
        $tableName = ProfessionalQa::getTable();

        return ProfessionalQa::when(is_id($cityId), function ($query) use ($tableName, $cityId) {
            $query->leftJoin('member_info mi', "$tableName.answer_memberId=mi.memberId")->where('mi.cityId', $cityId);
        })
            ->where("$tableName.isEnd", '1l')
            ->where("$tableName.checkStatus", '1')
            ->tableField(['id', 'question', 'answer_memberId', 'answer', 'answer_time',], $tableName)
            ->with([
                'answerMember' => fn($query) => $query->field(['id', 'nickname', 'headImgUrl'])
                    ->with([
                        'memberInfo' => fn($subQuery) => $subQuery->field([
                            'memberId',
                            'realname',
                            'professionalField',
                            'provinceId',
                            'cityId',
                        ])->with([
                            'province' => fn($query) => $query->shortArea(),
                            'city' => fn($query) => $query->shortArea(),
                        ])->hidden(['provinceId', 'cityId'])
                    ])
                    ->append(['headImg', 'headImgThumb'])
                    ->hidden(['headImgUrl'])
            ])
            ->order("$tableName.answer_time", 'DESC')
            ->limit($number)
            ->select();
    }
}
